import locationDefault from "@/assets/image/location-selected.png";
import locationSelected from "@/assets/image/location-icon-32.png";
import school from "@/assets/image/school-icon-32.png";
import hospital from "@/assets/image/hospital-icon-32.png";
import restaurant from "@/assets/image/restaurant-icon-32.png";
import tourist from "@/assets/image/tourist-icon-32.png";
import rescue from  "@/assets/image/rescue-icon-32.png";
import petrol from  "@/assets/image/petrol-station-icon-32.png";
import enterprise from "@/assets/image/enterprise-icon-32.png";
import belief from "@/assets/image/belief-icon-32.png";
import supermarket from "@/assets/image/supermarket-icon-32.png";
export const initAMapSecurity = () => {
  if (!window._AMapSecurityConfig) {
    window._AMapSecurityConfig = {
      securityJsCode: process.env.VUE_APP_AMAP_SEC_CODE
    };
  }
}

 // 简化版坐标系转换函数（实际项目中应使用更精确的算法）
export function wgs84ToGcj02(lng, lat) {
    // 简化的转换公式 - 实际应用中应使用更精确的转换算法
    const dLat = (Math.random() * 0.01) - 0.005;
    const dLng = (Math.random() * 0.01) - 0.005;
    
    return [lng + dLng, lat + dLat];
}

// 递归转换GeoJSON坐标
export function convertGeoJSONCoordinates(coordinates) {
    if (Array.isArray(coordinates[0])) {
        return coordinates.map(convertGeoJSONCoordinates);
    }
    
    return wgs84ToGcj02(coordinates[0], coordinates[1]);
}

// 转换整个GeoJSON对象
/**
 * 将 GeoJSON 对象转换为另一种格式
 *
 * @param geojson GeoJSON 对象
 * @returns 转换后的 GeoJSON 对象
 */
export function convertGeoJSON(geojson) {
    const converted = JSON.parse(JSON.stringify(geojson));
    function convertGeometry(geometry) {
        if (!geometry) return;
        
        if (geometry.type === 'Point') {
            geometry.coordinates = convertGeoJSONCoordinates(geometry.coordinates);
        } else if (geometry.type === 'LineString' || geometry.type === 'MultiPoint') {
            geometry.coordinates = geometry.coordinates.map(convertGeoJSONCoordinates);
        } else if (geometry.type === 'Polygon' || geometry.type === 'MultiLineString') {
            geometry.coordinates = geometry.coordinates.map(ring => 
                ring.map(convertGeoJSONCoordinates)
            );
        } else if (geometry.type === 'MultiPolygon') {
            geometry.coordinates = geometry.coordinates.map(polygon => 
                polygon.map(ring => 
                    ring.map(convertGeoJSONCoordinates)
                )
            );
        }
    }
    if (converted.type === 'FeatureCollection') {
        converted.features.forEach(feature => {
            convertGeometry(feature.geometry);
        });
    } else if (converted.type === 'Feature') {
        convertGeometry(converted.geometry);
    } else {
        convertGeometry(converted);
    }
    return converted;
}
declare const AMap: any;

// 定义类型
type SubColors = Record<string, string>;

interface SubGroupConfig {
  baseColor: string;
  subColors: SubColors;
}

interface CategoryGroupConfig {
  baseColor: string;
  subColors?: SubColors;
  subGroups?: Record<string, SubGroupConfig>;
}

type CategoryColorGroups = Record<string, CategoryGroupConfig>;

// 定义大类颜色映射
export const categoryColorGroups:CategoryColorGroups = {
  // 承载体 - 公共服务设施 (蓝色系)
  '承载体-公共服务设施': {
    baseColor: '#1E88E5',
    subColors: {
      '学校': '#0D47A1',
      '星级饭店': '#1976D2',
      '医疗卫生机构': '#2196F3',
      '化工园区': '#64B5F6',
      '提供住宿的社会服务机构': '#90CAF9',
      '公共文化场所': '#BBDEFB',
      '旅游景区': '#42A5F5',
      '体育场馆': '#1565C0',
      '宗教活动场所': '#5C6BC0',
      '大型超市、百货店和亿元以上商品交易市场': '#1E88E5',
      '县域基础指标统计表': '#0D47A1',
      '乡(镇)基础指标统计表': '#1976D2',
      '日日日日日日': '#2196F3' // 示例颜色，请替换实际类别
    }
  },
  
  // 承载体 - 危险化学品 (红色系)
  '承载体-危险化学品': {
    baseColor: '#E53935',
    subColors: {
      '化工园区': '#B71C1C',
      '企业基础信息': '#C62828',
      '加油加气加氢站': '#D32F2F',
      '自然灾吉承灾体-化工园区': '#E53935', // 注意原文本可能有错字
      '自然灾吉承灾体-企业基础信息': '#F44336',
      '自然灾吉承灾体-加油加气加氢站': '#EF5350'
    }
  },
  
  // 承载体 - 非煤矿山 (橙色系)
  '承载体-非煤矿山': {
    baseColor: '#FB8C00',
    subColors: {
      '金属非金属地下矿山承灾体': '#E65100',
      '金属非金属露天矿山承灾体': '#EF6C00',
      '尾矿库承灾体': '#F57C00',
      '自然灾害承灾休-金属非金属地下矿山承灾体': '#FF9800', // 注意原文本可能有错字
      '自然灾害承灾休-金属非金属露天矿山承灾体': '#FFA726',
      '自然灾害承灾休-尾矿库承灾体': '#FFB74D'
    }
  },
  
  // 承载体 - 煤矿 (棕色系)
  '承载体-煤矿': {
    baseColor: '#6D4C41',
    subColors: {
      '煤矿': '#4E342E',
      '自然灾害承灾体-煤矿': '#5D4037'
    }
  },
  
  // 减灾能力 (绿色系)
  '减灾能力': {
    baseColor: '#43A047',
    subGroups: {
      // 政府减灾能力
      '政府减灾能力': {
        baseColor: '#2E7D32',
        subColors: {
          '综合减灾资金投入': '#1B5E20',
          '航空护林站队伍与装备': '#388E3C',
          '地震专业救援队伍与装备': '#4CAF50',
          '矿山/隧道行业救援队伍与装备': '#66BB6A',
          '危化/油气行业救援队伍与装备': '#81C784',
          '海事救援队伍与装备': '#A5D6A7'
        }
      },
      
      // 企业与社会组织
      '企业与社会组织': {
        baseColor: '#689F38',
        subColors: {
          '大型企业救援装备和专职救援队伍': '#558B2F',
          '保险和再保险企业减灾能': '#7CB342',
          '社会组织减灾能力': '#9CCC65'
        }
      },
      
      // 乡镇与社区
      '乡镇与社区': {
        baseColor: '#7CB342',
        subColors: {
          '乡镇(街道)减灾能力': '#689F38',
          '社区(行政村)减灾能力': '#9CCC65',
          '应急避难场所': '#C5E1A5'
        }
      }
    }
  },
  
  // 历史灾害 (紫色系)
  '历史灾害': {
    baseColor: '#8E24AA',
    subColors: {
      '历史灾害': '#6A1B9A',
      '历史灾害-历史灾害': '#9C27B0'
    }
  },
  
  // 默认类别
  'default': {
    baseColor: '#9E9E9E',
    subColors: {
      'default': '#757575'
    }
  }
};


// 定义类别到图片的映射关系
const categoryIconMap: Record<string, string> = {
  // 学校相关类别
  "学校": school,
  "教育机构": school,
  "幼儿园": school,
  
  // 医疗相关类别
  "医院": hospital,
  "医疗卫生机构": hospital,
  "诊所": hospital,
  "卫生院": hospital,
  
  // 其他类别可以继续添加...
  "星级饭店":restaurant,
  "旅游景区":tourist,
  "救援":rescue,
  "加油":petrol,
  "企业":enterprise,
  "文化场所":belief,
  "大型超市":supermarket,
  // 默认图标
  "default": locationDefault,
  "selected": locationSelected
};


// 辅助函数：根据完整类别名称获取颜色
export function getCategoryColor(fullCategory) {
  if (!fullCategory) return categoryColorGroups.default.baseColor;
  
  // 尝试匹配顶级分类
  for (const [group, config] of Object.entries(categoryColorGroups)) {
    if (fullCategory.startsWith(group)) {
      const subCategory:any = fullCategory.substring(group.length + 1); // 去掉大类前缀
      
      // 特殊处理减灾能力的三级分类
      if (group === '减灾能力' && config.subGroups) {
        for (const [subGroup, subConfig] of Object.entries(config.subGroups)) {
          if (subCategory.startsWith(subGroup)) {
            const finalCategory = subCategory.substring(subGroup.length + 1);
            return subConfig.subColors[finalCategory] || subConfig.baseColor;
          }
        }
      }
      
      // 处理其他二级分类
      if (config.subColors) {
        return config.subColors[subCategory] || config.baseColor;
      }
      
      return config.baseColor;
    }
  }
  
  return categoryColorGroups.default.baseColor;
}

/**
 * 根据类别获取对应的图标
 * @param category - 类别名称
 * @param isSelected - 是否被选中状态
 * @returns 图标URL
 */
export function getIconByCategory(category: any, isSelected: any = false) {
  if (isSelected) {
    return locationSelected; // 选中状态统一使用选中的图标
  }
  
  // 查找匹配的图标
  const matchedKey = Object.keys(categoryIconMap).find(key => 
    category.includes(key)
  );
  
  return matchedKey ? categoryIconMap[matchedKey] : categoryIconMap.default;
}


export function getGeoJsonLayer(geoData, defaultStyle) {  
    return  new AMap.GeoJSON({
        geoJSON: geoData,
        getPolygon: function(geojson, lnglats) {
            const fullCategory = geojson.properties?.category || 'default';
      
            // 获取类别对应的颜色
            const color = getCategoryColor(fullCategory);
            const polygon =  new AMap.Polygon({
                path: lnglats,
                fillOpacity: defaultStyle.opacity,// 面积越大透明度越高
                strokeColor: color || defaultStyle?.stroke,
                fillColor: color + '80' || defaultStyle.fill,
                strokeWeight: defaultStyle.width,
                zIndex: defaultStyle.zIndex,
                cursor: 'pointer', // 添加指针样式
                bubble: true // 允许事件冒泡
            });
            if(!geojson.properties){
                geojson.properties = {};
            }
            if(defaultStyle.stroke){
                
                geojson.properties['stroke'] =  color || defaultStyle?.stroke;
            }
            // 更新stroke颜色信息，以便后续使用
            if(defaultStyle.fill){
                geojson.properties.fill =  color + '80' || defaultStyle.fill;
            }
         
            polygon.setExtData(geojson.properties);
            return polygon;
        },
        getMarker: function(geojson) {
            // 获取完整类别
            const properties = geojson.properties || {};
            const category = properties.category || 'default';
            const isSelected = properties.isSelected || false;
            
            // 根据类别和选择状态获取图标
            const iconUrl = getIconByCategory(category, isSelected);
            
            const marker = new AMap.Marker({
                position: geojson.geometry.coordinates,
                icon: new AMap.Icon({
                    image: iconUrl,
                    size: new AMap.Size(32, 32),
                    anchor: 'center'
                })
            });
            properties.iconUrl = iconUrl;
            marker.setExtData(properties);
            return marker;
        }
    });
}

// 辅助函数：动态创建带颜色的标记
export function createColoredMarker(color, category) {
  const canvas = document.createElement('canvas');
  const size = 16;
  canvas.width = size;
  canvas.height = size;
  const ctx:any = canvas.getContext('2d');
  
  // 绘制背景圆形
  ctx.beginPath();
  ctx.arc(size/2, size/2, size/2 - 1, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
  
  // 添加白色描边
  ctx.lineWidth = 1.5;
  ctx.strokeStyle = '#FFFFFF';
  ctx.stroke();
  
  // 根据类别添加简写标识
  if (category) {
    ctx.font = 'bold 10px Arial';
    ctx.fillStyle = '#FFFFFF';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // 获取类别首字母缩写
    let abbreviation = '';
    if (category.includes('-')) {
      // 取每部分的首字母
      abbreviation = category.split('-')
        .map(part => part.charAt(0))
        .join('')
        .substring(0, 3);
    } else {
      // 直接取前2个字符
      abbreviation = category.substring(0, 2);
    }
    
    ctx.fillText(abbreviation, size/2, size/2);
  }
  
  return canvas;
}
export function getRequiredPlugins(searchVisible) {
    const plugins = ['AMap.Marker',"AMap.Walking","AMap.Scale","AMap.ControlBar"];
    if (searchVisible) {
        plugins.push('AMap.PlaceSearch', 'AMap.AutoComplete');
    }
    return plugins;
}

export function zoomToPolyline(map:any, feature: any) {
  const path = feature.getPath(); 
  const bounds = new AMap.Bounds();
  
  path.forEach((point:  any) => {
    bounds.extend(point); 
  });
  
  map.setFitView(bounds); 
}

export function zoomToPolygon(map: any, feature: any) {
 map.setCenter(feature.extData.center.split(','));
}

export function zoomToCircle(map:any, feature: any) {
  const center = feature.getCenter(); 
//   const radius = feature.getRadius(); 
  
//   // 计算包含圆形的边界框
//   const bounds = new AMap.Bounds(center);
//   bounds.extend(AMap.GeometryUtil.getBoundaryPoint(center,  radius, 0));
//   bounds.extend(AMap.GeometryUtil.getBoundaryPoint(center,  radius, 90));
  
  map.setCenter(center); 
}

export function zoomToMarker(map: any, feature: any) {
  const position = feature.getPosition(); 
  map.setCenter(position); 
  map.setZoom(15);  // 设置合适的缩放级别 
}

/**
 * 根据地图实例和特征对象，处理缩放操作
 *
 * @param map 地图实例
 * @param feature 特征对象，包含extData属性，其中type表示特征类型
 */
export function  handleZoomToFeature(map:any, feature: any) {
 // 获取高德地图实例 

  const type = feature.extData.type; 
  
  switch(type) {
    case 'AMap.Marker':
      zoomToMarker(map,  feature);
      break;
    case 'Overlay.Circle':
      zoomToCircle(map,  feature);
      break;
    case 'Overlay.Polygon':
    case 'Overlay.Rectangle':
       case 'AMap.Polygon':
      zoomToPolygon(map,  feature);
      break;
    case 'Overlay.Polyline':
      zoomToPolyline(map,  feature);
      break;
  }
}
export const selectLocation = locationSelected;
export const defaultLocation = locationDefault;